package com.escapeicon.vision.utils;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;

/**
 * 阿里云短信服务 api
 * 1. 引入依赖
 * <dependency>
 *     <groupId>com.aliyun</groupId>
 *     <artifactId>dysmsapi20170525</artifactId>
 *     <version>2.0.24</version>
 * </dependency>
 */
public class SmsUtil {

    private static final String SIGN_NAME = "";// 2. 填写短信签名
    private static final String TEMPLATE_CODE = "";// 3. 填写模板代码
    private static final String ACCESS_KEY_ID = "";// 4. 填写 AccessId
    private static final String ACCESS_KEY_SECRET = "";// 5. 填写 AccessSecret
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";// 6. 填写 endpoint （无要求） 参考 https://api.aliyun.com/product/Dysmsapi

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    private static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = ENDPOINT;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 7. 调用方法传参
     * @param phoneNumbers 7.1 接收验证码的手机号
     * @param code 7.2 验证码
     * @return 短信状态信息
     * @throws Exception
     */
    public static SendSmsResponse sendMessage(String phoneNumbers,String code) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(SIGN_NAME)
                .setTemplateCode(TEMPLATE_CODE)
                .setPhoneNumbers(phoneNumbers)
                .setTemplateParam("{\"code\":"+code+"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        SendSmsResponse sendSmsResponse = new SendSmsResponse();
        try {
            sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return sendSmsResponse;
    }
}
